package com.kotei;

import cn.hutool.http.HttpUtil;
import com.kotei.config.MyBatisPlusConfig;
import com.kotei.mapper.ObsCompareMapper;
import com.kotei.pojo.ObsCompare;
import com.kotei.util.DownConst;
import com.kotei.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 对比失败附件下载工具
 */
@Slf4j
public class DownDownload {


    public static void main(String[] args) {
//        int status = HttpUtil.createGet("https://bigsatellite-datasync.obs.cn-north-4.myhuaweicloud.com/350000/350100/350181/35018120230301C00007/3fe85285-0959-4b85-b677-c40a73915ab8.jpg").execute().getStatus();
//        System.out.println(status);
        startDwon();

        String stt = "https://bigsatellite-datasync.obs.cn-north-4.myhuaweicloud.com/350000/350100/350181/35018120230301C00007/3fe85285-0959-4b85-b677-c40a73915ab8.jpg";

    }


    static void startDwon() {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        ThreadUtils threadUtils = new ThreadUtils();
        ExecutorService customThreadPool = threadUtils.getCustomThreadPool();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("开始时间\t" + sdf.format(new Date()));

        SqlSessionFactory sqlSessionFactory = MyBatisPlusConfig.getSqlSessionFactory();
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            // 获取对比失败数据并分组
            ObsCompareMapper obsCompareMapperSel = session.getMapper(ObsCompareMapper.class);
            List<ObsCompare> allList = obsCompareMapperSel.getAllList();
            System.out.println("总数据量-" + allList.size());
            List<List<ObsCompare>> partition = ListUtils.partition(allList, 1000);

            for (int index = 0; index < partition.size(); index++) {
                // 每1000条一个线程获取数据
                List<ObsCompare> obsCompares = partition.get(index);

                // 加入线程去下载附件
                customThreadPool.execute(() -> {
                    System.out.println("当前线程：" + Thread.currentThread().getName());
                    try (SqlSession session1 = sqlSessionFactory.openSession(true)) {
                        ObsCompareMapper obsCompareMapperUpd = session1.getMapper(ObsCompareMapper.class);
                        System.out.println("开始执行");
                        Iterator<ObsCompare> obsCompareIterator = obsCompares.iterator();

                        // 需要修改附件下载状态的
                        List<String> updateExistsStatusIds = new ArrayList<>();
                        // 开始迭代每一条附件
                        while (obsCompareIterator.hasNext()) {
                            ObsCompare obsCompare = obsCompareIterator.next();

                            // 验证http链接是否可用
                            int status = HttpUtil.createGet(obsCompare.getAbsolute_path()).execute().getStatus();
                            if (status == 200) {
                                // 加入到修改列表
                                updateExistsStatusIds.add(obsCompare.getId());

                                // 下载数据到附件列表
                                // 桶名获取
                                String bucketName = obsCompare.getAbsolute_path().substring(8, obsCompare.getAbsolute_path().indexOf("."));
                                String nasPath = DownConst.prefix + bucketName + "/" + obsCompare.getRelative_path();
                                try {
                                    HttpUtil.downloadFile(obsCompare.getAbsolute_path(), nasPath);
                                } catch (Exception e) {
                                    System.out.println("下载失败：" + obsCompare.getId());
                                }


                            }

                            if (CollectionUtils.isNotEmpty(updateExistsStatusIds) && (updateExistsStatusIds.size() == 500 || !obsCompareIterator.hasNext())) {
                                obsCompareMapperUpd.updateObsCompareExistStatus(updateExistsStatusIds);
                                updateExistsStatusIds.clear();
                                int i = atomicInteger.incrementAndGet();
                                System.out.println(String.format("写入\t%s\t%d", Thread.currentThread().getName(), i));
                            }
                        }
                        System.out.println("结束时间\t" + sdf.format(new Date()));
                    }

                });

            }

        }

    }


}